package com.jader.activities;

/*个人中心*/
import java.io.File;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jader.beans.User;
import com.jader.myviews.ActionSheetDialog;
import com.jader.myviews.ActionSheetDialog.OnSheetItemClickListener;
import com.jader.myviews.ActionSheetDialog.SheetItemColor;
import com.jader.util.CommonUtils;
import com.jader.util.JaderApplication;
import com.jader.util.PreferenceUtil;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest.HttpMethod;
import com.zlp.jader.R;

public class UserInfoActivity extends Activity implements OnClickListener {
	private TextView tv_user_name, tv_user_gender, tv_change_phone,
			tv_change_password;
	private RelativeLayout userPicLayout, userNameLayout, genderLayout;
	private Button btn_exit;
	private ImageView img_user_pic, img_person_back;
	private static final int PHOTO_REQUEST_CAMERA = 1;// 拍照
	private static final int PHOTO_REQUEST_GALLERY = 2;// 从相册中选择
	private static final String PHOTO_FILE_NAME = "jader.jpg";// 头像名称
	private File tempFile;
	private Bitmap bitmap;
	private HttpUtils httpUtils;
	private String url = JaderApplication.getIP() + "/Jader/client";
	// 获取图片地址
	ContentResolver resolver;
	private User user;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_user_info);
		user = JaderApplication.user;
		initView();
		inintUserInfo();
	}

	private void inintUserInfo() {
		String userPic = user.getPicture();
		if (userPic != null) {
			JaderApplication.getBitmapUtils().display(img_user_pic,
					JaderApplication.getIP() + "/Jader" + userPic);
		} else {
			img_user_pic.setImageResource(R.drawable.moren);
		}
		String userName = user.getUsername();
		String gender = user.getGender();

		tv_user_name.setText(userName);
		tv_user_gender.setText(gender);
	}

	/**
	 * 初始化视图中的控件
	 */
	private void initView() {
		img_person_back = (ImageView) findViewById(R.id.personale_back);
		btn_exit = (Button) findViewById(R.id.btn_exit);
		tv_user_name = (TextView) findViewById(R.id.tv_user_name);
		tv_user_gender = (TextView) findViewById(R.id.tv_user_gender);
		img_user_pic = (ImageView) findViewById(R.id.img_user_pic);
		tv_change_password = (TextView) findViewById(R.id.tv_userinfo_password);
		tv_change_phone = (TextView) findViewById(R.id.tv_userinfo_phone);
		userNameLayout = (RelativeLayout) findViewById(R.id.layout_userinfo_username);
		userPicLayout = (RelativeLayout) findViewById(R.id.layout_userinfo_picture);
		genderLayout = (RelativeLayout) findViewById(R.id.layout_userinfo_gender);
		// 单击事件
		userPicLayout.setOnClickListener(this);
		userNameLayout.setOnClickListener(this);
		genderLayout.setOnClickListener(this);
		tv_change_password.setOnClickListener(this);
		tv_change_phone.setOnClickListener(this);
		tv_user_name.setOnClickListener(this);
		tv_user_gender.setOnClickListener(this);
		img_user_pic.setOnClickListener(this);
		btn_exit.setOnClickListener(this);
		img_person_back.setOnClickListener(this);
	}

	/**
	 * 每个属性的单击事件
	 */
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.layout_userinfo_picture:
			// 更改头像图片
			Change_userPic();
			break;
		case R.id.layout_userinfo_username:
			// 修改昵称
			Change_name();
			break;
		case R.id.layout_userinfo_gender:
			// 修改性别
			Change_Gender();
			break;
		case R.id.tv_userinfo_phone:
			// 修改手机号 跳转到获取验证码界面
			Intent change_phone = new Intent(this, SetPhoneActivity.class);
			startActivity(change_phone);
			break;
		case R.id.tv_userinfo_password:
			Intent changePassWord = new Intent(this, ForgetActivity.class);
			startActivity(changePassWord);
			break;
		case R.id.btn_exit:
			// 退出账户,清除缓存账号信息
			clean();
			break;
		case R.id.personale_back:
			finish();
			break;
		case R.id.img_user_pic:
			// 更改头像图片
			Change_userPic();
			break;
		default:
			break;
		}
	}

	private void Change_userPic() {
		new ActionSheetDialog(this)
				.builder()
				.addSheetItem("立即拍照", SheetItemColor.Black,
						new OnSheetItemClickListener() {
							@Override
							public void onClick(int which) {
								ChangePicByPhoto();
							}
						})
				.addSheetItem("本地相册", SheetItemColor.Black,
						new OnSheetItemClickListener() {
							@Override
							public void onClick(int which) {
								ChangePicFromLocal();
							}
						}).show();
	}

	/** 相机拍照换头像 */
	protected void ChangePicByPhoto() {
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		if (CommonUtils.isExitsSdcard()) {
			intent.putExtra(MediaStore.EXTRA_OUTPUT,
					Uri.fromFile(new File(Environment
							.getExternalStorageDirectory(), PHOTO_FILE_NAME)));
		}
		startActivityForResult(intent, PHOTO_REQUEST_CAMERA);
	}

	/** 从图库获取图片 */
	protected void ChangePicFromLocal() {
		Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
		intent.addCategory(Intent.CATEGORY_OPENABLE);
		intent.setType("image/*");
		startActivityForResult(intent, PHOTO_REQUEST_GALLERY);
	}

	/** 上传图片 */
	private void upLoad(String url) {
		String picUrl = JaderApplication.getIP() + "/Jader/picture";
		httpUtils = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addBodyParameter("userid", user.getUserid() + "");
		params.addBodyParameter("photo", tempFile);
		Log.e("userPic", tempFile.toString());
		httpUtils.send(HttpMethod.POST, picUrl, params,
				new RequestCallBack<String>() {

					@Override
					public void onFailure(HttpException arg0, String arg1) {
						JaderApplication.show(getBaseContext(), arg1);
					}

					@Override
					public void onSuccess(ResponseInfo<String> info) {
						String result = info.result;
						JaderApplication.show(getBaseContext(), "更新成功");
						JaderApplication.getBitmapUtils().display(img_user_pic,
								JaderApplication.getIP() + "/Jader" + result);
						PreferenceUtil.getInstance(getBaseContext())
								.setShareUserPic(result);
						UserInfoActivity.this.user.setPicture(result);
					}
				});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == PHOTO_REQUEST_GALLERY) {
			if (data != null) {
				// 得到图片的全路径
				Uri uri = data.getData();
				tempFile = new File(getAbsoluteImagePath(uri));
				bitmap = BitmapFactory.decodeFile(getAbsoluteImagePath(uri));
				img_user_pic.setImageBitmap(bitmap);
				upLoad(url);
			}
		} else if (requestCode == PHOTO_REQUEST_CAMERA) {
			if (CommonUtils.isExitsSdcard()) {
				String path = Environment.getExternalStorageDirectory()
						.getPath() + "/" + PHOTO_FILE_NAME;
				tempFile = new File(path);
				bitmap = BitmapFactory.decodeFile(path);
				img_user_pic.setImageBitmap(bitmap);
				upLoad(url);
			} else {
				JaderApplication.show(this, "未找到SD卡存储路径");
			}
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	/** 修改名字 */
	private void Change_name() {
		final com.jader.myviews.AlertDialog dialog = new com.jader.myviews.AlertDialog(
				this).builder().setTitle("请输入新昵称").setMsg();
		dialog.setPositiveButton("确定", new OnClickListener() {

			@Override
			public void onClick(View v) {
				final String newName = dialog.getText();
				httpUtils = new HttpUtils();
				RequestParams params = new RequestParams();
				params.addBodyParameter("type", ""
						+ JaderApplication.UPDATE_USERNAME);
				params.addBodyParameter("username", newName);
				params.addBodyParameter("userid", user.getUserid() + "");
				httpUtils.send(HttpMethod.POST, url, params,
						new RequestCallBack<String>() {

							@Override
							public void onFailure(HttpException arg0,
									String arg1) {
								JaderApplication.show(getBaseContext(), "连接失败");
							}

							@Override
							public void onSuccess(ResponseInfo<String> arg0) {
								JaderApplication.show(getBaseContext(), "更新成功");
								tv_user_name.setText(newName);
								user.setUsername(newName);
								PreferenceUtil.getInstance(getBaseContext())
										.setShareUserName(newName);
							}
						});
			}
		}).setNegativeButton("取消", null).show();
	}

	private void Change_Gender() {
		new ActionSheetDialog(this)
				.builder()
				.addSheetItem("男", SheetItemColor.Black,
						new OnSheetItemClickListener() {
							@Override
							public void onClick(int which) {
								GenderRequest(which);
							}
						})
				.addSheetItem("女", SheetItemColor.Black,
						new OnSheetItemClickListener() {
							@Override
							public void onClick(int which) {
								GenderRequest(which);
							}
						}).show();
	}

	private void GenderRequest(int which) {
		final String userGender;
		if (which == 1) {
			userGender = "男";
		} else {
			userGender = "女";
		}
		httpUtils = new HttpUtils();
		RequestParams params = new RequestParams();
		params.addBodyParameter("type", "" + JaderApplication.UPDATE_USERGENDER);
		params.addBodyParameter("userid", user.getUserid() + "");
		params.addBodyParameter("gender", userGender);
		httpUtils.send(HttpMethod.POST, url, params,
				new RequestCallBack<String>() {
					@Override
					public void onFailure(HttpException arg0, String arg1) {
						JaderApplication.show(getBaseContext(), arg1);
					}

					@Override
					public void onSuccess(ResponseInfo<String> info) {
						String result = info.result;
						if (result.equals("success")) {
							JaderApplication.show(getBaseContext(), "更新成功");
							PreferenceUtil.getInstance(getBaseContext())
									.setShareUserGender(userGender);
							user.setGender(userGender);
							tv_user_gender.setText(userGender);
						} else {
							JaderApplication.show(getBaseContext(), "更新失败");
							tv_user_gender.setText("");
						}
					}
				});
	}

	/** 清除账号缓存 */
	private void clean() {
		PreferenceUtil.getInstance(getBaseContext()).cleanUserInfo();
		JaderApplication.user = null;
		finish();
		startActivity(new Intent(this, LoginActivity.class));
	}

	// 取到相册照片的绝对路径
	protected String getAbsoluteImagePath(Uri uri) {
		resolver = getContentResolver();
		String[] proj = { MediaStore.Images.Media.DATA };
		Cursor cursor = resolver.query(uri,// 地址
				proj, // Which columns to return 自己建的数组，里边存放需查询的数据
				null, // WHERE clause; which rows to return (all rows)where语句
				null, // WHERE clause selection arguments (none)where中？占位符组成的数组
				null); // Order-by clause (ascending by name)排序
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		return cursor.getString(column_index);
	}
}